package logic

import (
	"cart_srv/cache"
	"cart_srv/cartclient"
	"context"
	"fmt"
	"strconv"

	"cart_srv/cart"
	"cart_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListCartLogic {
	return &ListCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListCartLogic) ListCart(in *cart.ListCartRequest) (*cart.ListCartResponse, error) {
	// todo: add your logic here and delete this line

	key := fmt.Sprintf("cart:%d:*", in.UserId)
	keys, _ := cache.Rdb.Keys(l.ctx, key).Result()

	var cartList []*cartclient.ListCart
	for _, k := range keys {
		goodsMap := cache.Rdb.HGetAll(l.ctx, k).Val()

		price, _ := strconv.ParseFloat(goodsMap["Price"], 64)
		num, _ := strconv.Atoi(goodsMap["Num"])

		list := cartclient.ListCart{
			Title: goodsMap["Title"],
			Price: float32(price),
			Num:   int64(num),
		}
		cartList = append(cartList, &list)
	}

	return &cart.ListCartResponse{List: cartList}, nil
}
